package com.msz.controller;

import com.msz.domain.User;
import com.msz.service.UserService;
import com.msz.util.JwtUtils;
import com.msz.util.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 不拦截资源、放行controller
 * @author hx
 * @since 2021/12/5 16:56
 */
@Controller
@RequestMapping("/release")
@Api(tags = "放行资源")
public class ReleaseController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation("用户登录")
    @ResponseBody
    public R login(
            @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
            @ApiParam("密码") @RequestParam(value = "password",required = false) String password
    ){
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return R.result(500,"用户名与密码不能为空");
        }

        User user = userService.checkUser(new User(username, password));
        if (user == null) {
            return R.result(500,"用户名与密码不匹配");
        }else {
            //jwt生成token
            String jwtToken = JwtUtils.generatorJwtToken(user);

            //返回信息和token给客户端
            return R.result(200,"登录成功",jwtToken);
        }
    }


    @RequestMapping(value = "/check/token", method = RequestMethod.GET)
    @ApiOperation("检查token")
    @ResponseBody
    public R checkToken(@ApiParam("token字符串") @RequestParam("token") String token) {

        Jws<Claims> claimsJws = JwtUtils.checkToken(token);
        return R.result(200,"检测成功",claimsJws);
    }




//    @RequestMapping(value = "/logout",method = RequestMethod.GET)
//    @ApiOperation("用户注销")
//    @ResponseBody
//    public R logout(HttpSession session) {
//        try {
//            session.invalidate();
//            return R.result(200,"用户注销成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.result(500,"用户注销失败");
//        }
//    }
}
